﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Business;
using Core.Entity;

namespace TicketManagement.Ticket
{
    public partial class Request : System.Web.UI.Page
    {
        TicketBus bus = new TicketBus();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["User"] == null)
            {
                Response.Redirect("/User/Login.aspx", true);
            }

            if (!IsPostBack)
            {
                this.loadData();
            }

            this.displayServicePassword();
        }

        public void loadData()
        {
            this.loadAccountData();
            this.loadServiceType();
            this.loadDepartment();
            this.loadTicketCategory();
            this.loadService();
        }

        public void loadAccountData()
        {
            UserBus userBus = new UserBus();
            Core.Entity.User user = userBus.get((int)Session["User"]);

            AccountBus accountBus = new AccountBus();
            Core.Entity.Account account = accountBus.getAccountByUserId(user.Id);

            lblAccountCode.InnerText = account.Code;
            lblAccountName.InnerText = account.OwnerName;
            lblAccountEmail.InnerText = user.Email;
        }

        public void loadServiceType()
        {
            ServiceTypeBus serviceTypeBus = new ServiceTypeBus();
            List<Core.Entity.ServiceType> serviceTypes = serviceTypeBus.getAll(true);

            Core.Entity.ServiceType blank = new Core.Entity.ServiceType();
            blank.Id = -1;
            blank.Name = "--Chọn loại dịch vụ--";

            serviceTypes.Insert(0, blank);

            cmbServiceType.DataSource = serviceTypes;
            cmbServiceType.DataBind();
        }

        public void loadDepartment()
        {
            DepartmentBus departmentBus = new DepartmentBus();
            List<Core.Entity.Department> departments = departmentBus.getAll();

            Core.Entity.Department blank = new Core.Entity.Department();
            blank.Id = -1;
            blank.Name = "--Chọn phòng ban--";

            departments.Insert(0, blank);

            cmbDepartment.DataSource = departments;
            cmbDepartment.DataBind();
        }

        public void loadTicketCategory()
        {
            int serviceTypeId = Convert.ToInt32(cmbServiceType.SelectedValue);
            int departmentId = Convert.ToInt32(cmbDepartment.SelectedValue);

            TicketCategoryBus ticketCategoryBus = new TicketCategoryBus();
            List<Core.Entity.TicketCategory> ticketCategories = ticketCategoryBus.getAllByServiceTypeIdAndDepartmentId(serviceTypeId, departmentId);

            Core.Entity.TicketCategory blank = new Core.Entity.TicketCategory();
            blank.Id = -1;
            blank.Name = "--Vui lòng chọn chủ đề--";

            ticketCategories.Insert(0, blank);

            cmbTicketCategory.DataSource = ticketCategories;
            cmbTicketCategory.DataBind();
        }

        public void loadService()
        {
            AccountBus accountBus = new AccountBus();
            Core.Entity.Account account = accountBus.getAccountByUserId((int)Session["User"]);

            OrderBus orderBus = new OrderBus();
            List<Core.Entity.OrderLine> services = orderBus.getAllOrderLinesByAccountIdAndServiceId(account.Id, Convert.ToInt32(cmbServiceType.SelectedValue));

            Core.Entity.OrderLine blank = new Core.Entity.OrderLine();
            blank.Id = -1;
            blank.Desc = "--Chọn dịch vụ--";

            services.Insert(0, blank);

            cmbService.DataSource = services;
            cmbService.DataBind();
        }

        protected void cmbServiceType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.loadTicketCategory();
            this.loadService();
            this.displayServicePassword();
        }

        protected void cmbDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.loadTicketCategory();
        }

        protected void cmbService_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.displayServicePassword();
        }

        public void displayServicePassword() 
        {
            trServicePassword.Visible = false;

            if (cmbService.SelectedValue != null)
            {
                int orderLineId = Convert.ToInt32(cmbService.SelectedValue);

                if (orderLineId > 0)
                {
                    OrderLineBus orderLineBus = new OrderLineBus();
                    OrderLine orderLine = orderLineBus.get(orderLineId);

                    ServiceBus serviceBus = new ServiceBus();
                    Core.Entity.Service service = serviceBus.get(orderLine.ServiceId);

                    trServicePassword.Visible = true;

                    if (service.ServiceTypeId == 1)
                    {
                        lblServicePassword.InnerText = "Mật khẩu tên miền";
                    }
                    else
                    {
                        lblServicePassword.InnerText = "Mật khẩu hosting";
                    }
                }
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            this.save();
        }

        public void save()
        {
            AccountBus accountBus = new AccountBus();
            Core.Entity.Account account = accountBus.getAccountByUserId((int)Session["User"]);

            Core.Entity.Ticket ticket = new Core.Entity.Ticket();
            ticket.ParentId = account.Id;
            ticket.ParentType = "Account";
            ticket.TicketStatusId = 1; // New
            ticket.ServiceTypeId = Convert.ToInt32(cmbServiceType.SelectedValue);
            ticket.DepartmentId = Convert.ToInt32(cmbDepartment.SelectedValue);
            ticket.TicketCategoryId = Convert.ToInt32(cmbTicketCategory.SelectedValue);
            ticket.OrderLineId = Convert.ToInt32(cmbService.SelectedValue);
            ticket.Number = bus.issueNumber();
            ticket.ServicePassword = (ticket.ServiceTypeId > 0) ? txtServicePassword.Value : "";
            ticket.Subject = txtSubject.Value;
            ticket.Content = txtContent.Text;
            DateTime timeStamp = DateTime.Now;
            ticket.Attachment = this.saveAttachment(timeStamp);

            lblMessage.InnerHtml = "";

            if (bus.insert(ticket))
            {
                
                String script = "alert('Gửi yêu cầu thành công!'); location.href='/Ticket/NewRequest.aspx';";
                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", script, true);
            }
            else
            {
                lblMessage.InnerHtml = "Không gửi được yêu cầu. Vui lòng thử lại!";
            }
        }

        private String saveAttachment(DateTime timeStamp)
        {
            String fileName = "";
            HttpPostedFile file = txtFile.PostedFile;
            if (file != null && file.FileName != "")
            {
                try
                {
                    String imageName = timeStamp.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + file.FileName;
                    file.SaveAs(Server.MapPath("/Assets/data/" + imageName));
                    fileName = imageName;
                }
                catch (Exception ex) { }
            }
            return fileName;
        }

        protected void cmbValidator_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            if (e.Value == "-1")
            {
                e.IsValid = false;
            }
            else
            {
                e.IsValid = true;
            }
        }

    }
}